package com.sqx.modules.address.controller;

import com.sqx.common.utils.Result;
import com.sqx.modules.address.entity.Address;
import com.sqx.modules.address.service.AddressService;
import com.sqx.modules.app.annotation.Login;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.UserEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wuChang
 * @since 2023-08-10
 */
@RestController
@RequestMapping("/app/address/")
@Api(value = "用户地址用户端", tags = {"用户地址-用户端"})
public class AppAddressController {

    @Autowired
    private AddressService userAddressService;
    @Autowired
    private UserDao userDao;

    @Login
    @ApiOperation("保存地址")
    @PostMapping("saveAddress")
    public Result saveAddress(@RequestAttribute("userId") Long userId, Address address) {
        if (address.getAddressId() != null){
            UserEntity userEntity = userDao.selectById(userId);
            Address address1 = userAddressService.getById(address.getAddressId());
            if (address1 == null){
                return Result.error("该不存在地址");
            }
            if (!userEntity.getUserId().equals(address1.getUserId())){
                return Result.error("您没有权限操作此地址");
            }
        }
        address.setUserId(userId);
        return userAddressService.addAddress(address);
    }

//    @ApiOperation("保存地址")
//    @PostMapping("saveAddressByUser")
//    public Result saveAddress(SysUserAddress sysUserAddress) {
//        return userAddressService.saveAddress(sysUserAddress);
//    }
    @ApiOperation("获取地址详细信息")
    @GetMapping("getAddressInfo")
    public Result getAddressInfo(Long addressId) {
        return Result.success().put("data",userAddressService.getById(addressId));
    }

    @Login
    @ApiOperation("删除地址")
    @PostMapping("deleteAddress")
    public Result deleteAddress(@RequestAttribute("userId") Long userId, Long addressId) {
        return userAddressService.deleteAddress(userId,addressId);
    }

    @Login
    @ApiOperation("获取地址列表")
    @GetMapping("getAddressList")
    public Result getAddressList(@RequestAttribute("userId") Long userId, Integer page, Integer limit,Address address) {
        address.setUserId(userId);
        return Result.success(userAddressService.getAddressList(page, limit, address));
    }
}
